package cn.com.self.security.config;

import cn.com.self.apis.portal.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;

import javax.imageio.ImageIO;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDateTime;
import java.util.Random;

@Configuration
@ConditionalOnExpression("${self.auth.imagecode:false}")
public class ImageCodeConfiguration {

    public final static String SESSION_KEY_IMAGE_CODE = "SESSION_KEY_IMAGE_CODE";

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    @Autowired
    private RedisUtils redisUtils;

    public class ImageCode {

        private BufferedImage image;
        private String code;
        private LocalDateTime expireTime;

        public ImageCode(BufferedImage image, String code, int expireIn) {
            this.image = image;
            this.code = code;
            this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
        }

        boolean isExpire() {
            return LocalDateTime.now().isAfter(expireTime);
        }

        public BufferedImage getImage() {
            return image;
        }

        public void setImage(BufferedImage image) {
            this.image = image;
        }

        public String getCode() {
            return code;
        }

        public void setCode(String code) {
            this.code = code;
        }

        public LocalDateTime getExpireTime() {
            return expireTime;
        }

        public void setExpireTime(LocalDateTime expireTime) {
            this.expireTime = expireTime;
        }
    }

    @Autowired
    public void setHandlerMapping(RequestMappingInfoHandlerMapping mapping)
            throws NoSuchMethodException {
        mapping.registerMapping(RequestMappingInfo
                .paths("/imgcode").methods(RequestMethod.GET).build(), this, this.getClass().getMethod("createCode", HttpServletRequest.class, HttpServletResponse.class));
    }

    public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ImageCode imageCode = createImageCode();
        sessionStrategy.setAttribute(new ServletWebRequest(request), SESSION_KEY_IMAGE_CODE, imageCode);
        redisUtils.set(SESSION_KEY_IMAGE_CODE + imageCode.code,imageCode.code,60);
        //禁止图像缓存。
        //response.setHeader("Pragma", "no-cache");
        //response.setHeader("Cache-Control", "no-cache");
        ImageIO.write(imageCode.getImage(), "jpeg", response.getOutputStream());
    }


    @Bean
    public FilterRegistrationBean filterRegistration() {
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new OncePerRequestFilter() {
            @Override
            protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
                ServletWebRequest servletWebRequest = new ServletWebRequest(request);
                response.setHeader("Access-Control-Allow-Origin", request.getHeader("origin"));
                response.setHeader("Access-Control-Allow-Credentials", "true");

                //logger.info(response.getHeader("Access-Control-Allow-Origin"));
                try {
                    validateCode(servletWebRequest);
                } catch (IllegalArgumentException e) {
                    //response.sendError(HttpStatus.UNAUTHORIZED.value(), e.getMessage());
                    response.setStatus(HttpStatus.OK.value());
                    response.setCharacterEncoding("utf-8");
                    response.setContentType (  "application/json; charset=utf-8");
                    PrintWriter printWriter = response.getWriter();
                    printWriter.write("{ \"status\":"+ HttpStatus.UNAUTHORIZED.value()+", \"desc\":\""+ e.getMessage() +"\"}");
                    printWriter.flush();
                    return;
                }
                filterChain.doFilter(request, response);
            }
        });
        registration.addUrlPatterns("/oauth/token");

        return registration;
    }

    private ImageCode createImageCode() {
        int width = 65; // 验证码图片宽度
        int height = 25; // 验证码图片长度
        int length = 4;  // 验证码位数
        int expireIn = 60; // 验证码有效时间 60s

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        Graphics graphics = image.getGraphics();

        Random random = new Random();

        graphics.setColor(getRandColor(200, 500));
        graphics.fillRect(0, 0, width, height);
        graphics.setFont(new Font("Times New Roman", Font.ITALIC, 20));
        graphics.setColor(getRandColor(160, 200));
        for (int i = 0; i < 155; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(12);
            int yl = random.nextInt(12);
            graphics.drawLine(x, y, x + xl, y + yl);
        }
        StringBuilder sRand = new StringBuilder();
        for (int i = 0; i < length; i++) {
            String rand = String.valueOf(random.nextInt(10));
            sRand.append(rand);
            graphics.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            graphics.drawString(rand, 13 * i + 6, 16);
        }
        graphics.dispose();
        return new ImageCode(image, sRand.toString(), expireIn);
    }

    private Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255)
            fc = 255;

        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }


    private void validateCode(ServletWebRequest servletWebRequest) throws ServletRequestBindingException, AccessDeniedException {
        ImageCode codeInSession = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, SESSION_KEY_IMAGE_CODE);

        String codeInRequest = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "imgcode");
        String code = null;
        if(codeInSession == null){
            code = redisUtils.get(SESSION_KEY_IMAGE_CODE + codeInRequest).toString();
        }

        if (codeInSession == null && code == null) {
            throw new IllegalArgumentException("不存在验证码!");
        }

        if (StringUtils.isEmpty(codeInRequest)) {
            throw new IllegalArgumentException("未输入验证码!");
        }

        if(codeInSession != null ){
            if(!codeInSession.getCode().equals(codeInRequest)){
                throw new IllegalArgumentException("验证码不正确!");
            }
        }else{
            if (!codeInRequest.equals(code)) {
                throw new IllegalArgumentException("验证码不正确!");
            }
        }

    }

}
